package com.littlebee.storychild.common.http;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * author: xiejia
 * created at 2016/8/4 14:50
 * description:
 */
public class BaseRequest extends Request<String> {
    private int method = Method.GET;
    private Map<String, String> params = new LinkedHashMap<String, String>();
    private Response.Listener<String> listener;
    private int time_out = 30 * 1000;//超时时间
    private int retry_num = 0;//重试次数
    private float backoffMultiplier = 1.0f;//增长因子

    public BaseRequest(String url, Response.Listener listener, Response.ErrorListener errorListener) {
        this(Method.POST, url, listener, errorListener);
    }

    public BaseRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);

        this.listener = listener;
        this.method = method;

        //默认超时30s,重试次数0，增长因子1.0f
        setRetryPolicy(new DefaultRetryPolicy(time_out, retry_num, backoffMultiplier));
    }


    public void setParam(String key, double value) {
        params.put(key, String.valueOf(value));
    }

    public void setParam(String key, long value) {
        params.put(key, String.valueOf(value));
    }

    public void setParam(String key, int value) {
        params.put(key, String.valueOf(value));
    }

    public void setParam(String key, String value) {
        if (value != null) {
            params.put(key, value);
        }
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return params;
    }

    public Map<String, String> getParamsMap() {
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Charset", getParamsEncoding());
        headers.put("Content-Type", getBodyContentType());
        return headers;
    }


    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String reponse = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

            return Response.success(reponse, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(String response) {
        //super.deliverResponse(response);
        listener.onResponse(response);
    }
}

